<template>
  <Dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑批注' : '添加批注'"
    :width="600"
    :max-height="600"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      label-position="top"
    >
      <el-form-item label="批注内容" prop="content">
        <el-input
          v-model="formData.content"
          type="textarea"
          :rows="8"
          placeholder="请输入批注内容..."
          maxlength="1000"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, nextTick } from "vue";
import { Dialog } from "../dialog";
import type { FormInstance, FormRules } from "element-plus";

defineOptions({
  name: "CommentDialog",
});

interface Props {
  modelValue: boolean;
  commentId?: string;
  initialContent?: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  commentId: "",
  initialContent: "",
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "submit", content: string): void;
  (e: "close"): void;
}>();

const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const isEdit = computed(() => !!props.commentId);
const isSubmitted = ref(false); // 标记是否已提交

const formData = reactive({
  content: "",
});

const formRules: FormRules = {
  content: [
    { required: true, message: "请输入批注内容", trigger: "blur" },
    { min: 1, max: 1000, message: "批注内容长度在 1 到 1000 个字符", trigger: "blur" },
  ],
};

watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val;
    if (val) {
      formData.content = props.initialContent || "";
      isSubmitted.value = false; // 重置提交标记
      // 重置表单验证
      nextTick(() => {
        formRef.value?.clearValidate();
      });
    }
  },
  { immediate: true }
);

watch(dialogVisible, (val) => {
  emit("update:modelValue", val);
  if (!val && !isSubmitted.value) {
    // 只有当不是提交关闭时，才emit close事件
    emit("close");
  }
  // 重置提交标记
  if (!val) {
    isSubmitted.value = false;
  }
});

const handleClose = () => {
  dialogVisible.value = false;
  formData.content = "";
  formRef.value?.clearValidate();
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    isSubmitted.value = true; // 标记已提交
    emit("submit", formData.content);
    // 提交成功后关闭Dialog
    dialogVisible.value = false;
    formData.content = "";
    formRef.value?.clearValidate();
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form) {
  padding: 20px;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
  line-height: 1.6;
}
</style>

